/**
 * 主页面 - 报关单字段提取
 */
import React, { useState } from 'react';
import { Layout, Button, Space, message, Divider, Alert } from 'antd';
import { ThunderboltOutlined, ReloadOutlined } from '@ant-design/icons';
import FileUpload from '../components/FileUpload';
import ProgressBar from '../components/ProgressBar';
import ResultTable from '../components/ResultTable';
import ExportButtons from '../components/ExportButtons';
import { extractFields } from '../api/customs';
import type { ExtractedFields, ExtractionResponse } from '../types/customs';
import { transformFieldsData, generateExtractionResults } from '../utils/dataTransform';

const { Header, Content, Footer } = Layout;

type Status = 'idle' | 'uploading' | 'extracting' | 'success' | 'error';

const Home: React.FC = () => {
  const [files, setFiles] = useState<File[]>([]);
  const [status, setStatus] = useState<Status>('idle');
  const [progress, setProgress] = useState({ current: 0, total: 37 });
  const [extractedData, setExtractedData] = useState<ExtractedFields>({});
  const [extractionResults, setExtractionResults] = useState<any[]>([]);
  const [rawContents, setRawContents] = useState<Record<string, string>>({});  // 新增: 智能体原始content
  const [progressMessage, setProgressMessage] = useState<string>('');

  // 处理文件变化
  const handleFilesChange = (newFiles: File[]) => {
    setFiles(newFiles);
    // 清空之前的结果
    if (status === 'success') {
      setStatus('idle');
      setExtractedData({});
      setExtractionResults([]);
      setRawContents({});
    }
  };

  // 开始提取
  const handleExtract = async () => {
    if (files.length === 0) {
      message.warning('请先上传文件');
      return;
    }

    try {
      setStatus('uploading');
      setProgressMessage('正在上传文件到服务器...');
      setProgress({ current: 0, total: 37 });

      // 模拟上传进度
      setTimeout(() => {
        setStatus('extracting');
        setProgressMessage('正在解析文件并提取字段信息...');
      }, 500);

      // 调用API
      const response: ExtractionResponse = await extractFields(files);

      if (response.success) {
        setStatus('success');
        
        // 转换后端数据格式为前端格式
        const transformedData = transformFieldsData(response.data.fields_data);
        setExtractedData(transformedData);
        
        // 生成提取结果状态
        const extractionResults = generateExtractionResults(response.data.fields_data);
        setExtractionResults(extractionResults);
        
        // 保存智能体原始content内容
        setRawContents(response.data.raw_contents || {});
        
        // 更新进度信息
        const { total_fields, successful_fields, failed_fields } = response.data.extraction_summary;
        const successRate = total_fields > 0 ? (successful_fields / total_fields) * 100 : 0;
        
        setProgress({
          current: successful_fields,
          total: total_fields,
        });
        setProgressMessage(
          `成功提取 ${successful_fields}/${total_fields} 个字段 ` +
          `(成功率: ${successRate.toFixed(1)}%，失败: ${failed_fields}个)`
        );
        message.success('字段提取完成！');
      } else {
        throw new Error(response.message || '提取失败');
      }
    } catch (error) {
      console.error('提取错误:', error);
      setStatus('error');
      setProgressMessage('提取失败: ' + (error as Error).message);
      message.error('字段提取失败: ' + (error as Error).message);
    }
  };

  // 重新开始
  const handleReset = () => {
    setFiles([]);
    setStatus('idle');
    setProgress({ current: 0, total: 37 });
    setExtractedData({});
    setExtractionResults([]);
    setRawContents({});
    setProgressMessage('');
  };

  // 处理数据编辑
  const handleDataChange = (newData: ExtractedFields) => {
    setExtractedData(newData);
  };

  const isExtracting = status === 'uploading' || status === 'extracting';
  const hasResults = status === 'success' || status === 'error';

  return (
    <Layout style={{ minHeight: '100vh' }}>
      <Header style={{ background: '#fff', padding: '0 50px', boxShadow: '0 2px 8px rgba(0,0,0,0.1)' }}>
        <div style={{ display: 'flex', alignItems: 'center', height: '100%' }}>
          <div style={{ fontSize: '20px', fontWeight: 'bold', color: '#1890ff' }}>
            📋 报关单字段提取系统
          </div>
        </div>
      </Header>

      <Content style={{ padding: '24px 50px', maxWidth: '1400px', margin: '0 auto', width: '100%' }}>
        {/* 使用说明 */}
        <Alert
          message="使用说明"
          description="1. 上传报关单文件（支持PDF和图片格式）；2. 点击开始提取按钮；3. 等待AI自动提取字段信息；4. 查看和编辑提取结果；5. 导出为Excel、JSON或PDF格式"
          type="info"
          showIcon
          closable
          style={{ marginBottom: 24 }}
        />

        {/* 文件上传区域 */}
        <FileUpload onFilesChange={handleFilesChange} disabled={isExtracting} />

        {/* 操作按钮 */}
        <Space size="large" style={{ marginTop: 16, marginBottom: 24 }}>
          <Button
            type="primary"
            size="large"
            icon={<ThunderboltOutlined />}
            onClick={handleExtract}
            disabled={files.length === 0 || isExtracting}
            loading={isExtracting}
          >
            {isExtracting ? '正在提取...' : '开始提取字段'}
          </Button>

          {hasResults && (
            <Button
              size="large"
              icon={<ReloadOutlined />}
              onClick={handleReset}
            >
              重新上传
            </Button>
          )}
        </Space>

        {/* 进度条 */}
        <ProgressBar
          status={status}
          current={progress.current}
          total={progress.total}
          message={progressMessage}
        />

        {/* 结果展示 */}
        {status === 'success' && (
          <>
            <Divider />
            <ResultTable
              data={extractedData}
              onDataChange={handleDataChange}
              extractionResults={extractionResults}
              rawContents={rawContents}
            />
            
            {/* 导出按钮 */}
            <div style={{ textAlign: 'center', marginTop: 32 }}>
              <ExportButtons
                data={extractedData}
                files={files}
              />
            </div>
          </>
        )}

        {/* 错误提示 */}
        {status === 'error' && (
          <Alert
            message="提取失败"
            description={progressMessage}
            type="error"
            showIcon
            style={{ marginTop: 16 }}
          />
        )}
      </Content>

      <Footer style={{ textAlign: 'center', background: '#f0f2f5' }}>
        报关单字段提取系统 © 2025 | 基于AI智能提取技术
      </Footer>
    </Layout>
  );
};

export default Home;

